/**
 * 
 */
package org.cuatrovientos.javakart;


import java.util.Random;
import java.util.Vector;


/**
 * the most important race
 * @author david_madurga
 *
 */
public class Race {

	
	private String name;
	private Circuit myCircuit;
	private Vector<Car> people = new Vector<Car>();
	//private Hashtable<String,Car> people;
	
	/**
	 * Constructor
	 * @param name
	 * @param myCircuit
	 */
	public Race(String name, Circuit myCircuit) {
		this.name = name;
		this.myCircuit = myCircuit;
	}
	
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * Insert vehicles
	 * @param v
	 */
	public void insertCar(Car v){
		
		people.add(v);
	}
	
	/**
	 * Run vehicles and calculate crashes;
	 * @return
	 */
	public Car run(){
		
		int pole;
		int index=0;
		int pole2;
		 for (Car v: people){
		
			Random rnd= new Random();

				if (rnd.nextInt(4) == 2) {
					int problem =(int)(Math.random()*8+3);
					
					
					if ((v.manoeuvre()-problem)<3){
						System.out.println("The car " + v.getName() + " with number " + v.getNumber() + " is destroyer" );
						v.name=null;
						
						System.out.println("The race continue in 5 seconds");
						
						
						try{
						Thread.sleep(5000);
						} catch (InterruptedException ex) {}
					}
				}
		 }
		 
		 
		
		 int tam=people.size();
		for (int i =0 ;i < tam;i++){
			if (people.get(i).name==null){
				tam--;
				people.remove(i);
			}
			
		}
		 pole=1000;
		 for (int i=0;i< people.size();i++){
			pole2=timer(people.get(i));
			 if (pole2<pole){
				index=i;
				pole=pole2;
			}
		 }
		
		 return people.get(index);
		 
	}
	/**
	 * Calculate timer
	 * @param v
	 * @return
	 */
	private int timer(Car v){
		int seconds =0;
		int km=0;
		while (km < myCircuit.getKilometres()){
			seconds++;
			km+=v.move();
		}
		return seconds;
	}
		 
		 
	
	
	
}
